package com.yunchang.springboot.quatrz.scheduler;

import com.yunchang.springboot.mapper.base.BaseReportInfoMapper;
import com.yunchang.springboot.mapper.log.LogReportRecordMapper;
import com.yunchang.springboot.models.base.BaseReportInfo;
import com.yunchang.springboot.models.log.LogReportRecord;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

@Slf4j
@Component
@EnableScheduling
public class MwsReportErrorTestScheduler {
    @Value("${errorJobPath}")
    private String errorJobPath;

    /**
     * scheduler工厂bean，用于创建scheduler
     */
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    /**
     * 基础报告信息
     */
    @Autowired
    private BaseReportInfoMapper baseReportInfoMapper;

    /**
     * 获取报告过程日志记录
     */
    @Autowired
    private LogReportRecordMapper logReportRecordMapper;


    public void schedulerTest() throws SchedulerException {
        log.info("开始mws错误日期拉取数据测试，时间：" + LocalDateTime.now().toString());
        BaseReportInfo baseReportInfo = baseReportInfoMapper.selectOneById(12);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.start();
        String name = baseReportInfo.getJobName();
//        String groupName = baseReportInfo.getJobGroup();
        String cronExpression = baseReportInfo.getRerunCronExpression();
        String reportName = baseReportInfo.getChineseReportName();
        Class<? extends Job> jobClass = null;
        try {
            jobClass = (Class<? extends Job>) Class.forName(errorJobPath + baseReportInfo.getRerunJobClass());
        } catch (ClassNotFoundException e) {
            // 获取报告日志记录对象
            LogReportRecord logReportRecord = new LogReportRecord();
            logReportRecord.setReportInfoId(baseReportInfo.getId());
            logReportRecord.setRemarks("job类不存在!");
            logReportRecord.setAddTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            logReportRecord.setModTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            logReportRecordMapper.insertSelective(logReportRecord);
        }
        // 创建对应的job类
        JobDetail job = newJob(jobClass)
                .withIdentity(name, "error")
                .usingJobData("reportName", reportName)
                .usingJobData("reportType", baseReportInfo.getReportType())
                .usingJobData("timeScope", baseReportInfo.getReportTimeScope())
                .usingJobData("getReportArea", baseReportInfo.getGetReportArea())
                .usingJobData("reportInfoId", baseReportInfo.getId())
                .build();
        // 根据cron表达式创建触发器
        Trigger trigger = newTrigger()
                .withIdentity(name, "error")
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed())
                .build();
        // 将job和触发器作为参数启动scheduler
        scheduler.scheduleJob(job, trigger);
    }
}
